import EventBus from '../utils/eventBus';
import { startApp, endApp, createTest } from './template';

class GenerCode {
    constructor() {
        this.initEvent();
        this.callbacks = [];
        this.tests = []; //测试用例
    }
    initEvent() {
        EventBus.$on('start-app', (msg) => {
            this.render();

        })
        // 创建测试用例
        EventBus.$on('create-test', () => {
            this.tests.push([]);
            this.render();
        })

    }

    render() {
        let code = startApp();
        this.tests.forEach((test, index) => {
            code += createTest(test, index);
        })
        code += endApp();
        // 通知更新UI
        this.callbacks.forEach(fn => {
            fn(code)
        })
    }
    exec(name, value) {
        EventBus.$emit(name, value);
    }
    update(fn) {
        this.callbacks.push(fn);
    }
    // ----------
    addClick(selector) {

        const test = this.tests[this.tests.length - 1];
        test.push(
            `
    const button = await searchBox.$('.searchButton');
    await button.tap();
`
        )
        this.render();
    }
    addInput(selector, value) {
        const test = this.tests[this.tests.length - 1];
        test.push(
            `
    const searchBox = await page.$('search-box');
    const input = await searchBox.$('.searchInput');
    await input.input('医生');
`
        )
        this.render();
    }
    addScroll(selector, height) {
        const test = this.tests[this.tests.length - 1];
        test.push(
            `
    await miniProgram.pageScrollTo(20)
    console.log(await page.scrollTop())
`
        )
        this.render();
    }
}

export default GenerCode;